package oop.ex3.filemanager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;

public class FmListener implements Runnable{
	
	private static final int TIMEOUT = 5000;
	
	private ServerSocket _myServer;
	private FMContext _context;
	private ExecutorService _executor;
	
	/**
	 * constructor for FmListener. build a Server Socket
	 * @param port
	 * @throws IOException
	 */
	public FmListener(int port, FMContext context, 
			ExecutorService executor) throws IOException{
		
		_context = context;
		_executor = executor;
		//construct protocol Array

		//initial service socket
		_myServer = new ServerSocket(port);
//		_myServer.setSoTimeout(TIMEOUT);
	}

	@Override
	public void run() {
		//TODO set condition
		while(!_executor.isShutdown()){
			try {
				Socket s = _myServer.accept();
				if (!_executor.isShutdown()){
					UploadThread thread = new UploadThread(s , _context);
				_executor.execute(thread);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
		try {
			_myServer.close();
		} catch (IOException e) {
		}
	}
}
